<template>
  <div class="content">
    <div class="topBox" ref="topBox" :class="isFold ? 'paddingBottom' : ''">
      <div class="title">
        智能质检任务
        <span v-if="tableState.tableData.length > 0">
          <t-dropdown class="batch repeat" trigger="click" @click="clickQuality">
              <t-space>
                <t-button class="hoverBlue">
                  <span class="name">新增任务</span>
                  <svg-icon
                      :name="'icon-batchDown'"
                      class-name="batch-svg-icon"
                  ></svg-icon>
                </t-button>
              </t-space>
              <t-dropdown-menu>
                <t-dropdown-item class="batchItem" :value="0">智能质检</t-dropdown-item>
                <t-dropdown-item class="batchItem" :value="2">人工质检</t-dropdown-item>
                <t-dropdown-item class="batchItem" :value="1">标签质检</t-dropdown-item>
              </t-dropdown-menu>
            </t-dropdown>
        </span>
      </div>
      <div class="line" :class="isFold ? '' : 'lineBottom'"></div>
      <div class="formBox">

        <div class="titleFunnel" v-if="isFold" style="padding-bottom: 0">
          <div class="blueLine"></div>
          <div class="title">常用筛选</div>
        </div>
        <t-form
            ref="form"
            :data="formData"
            :layout="'inline'"
            scroll-to-first-error="smooth"

        >
          <t-form-item label="预设规则" name="presetsRule" :label-width="56">
            <t-select v-model="formData.presetsRule" @change="onPresetRuleChange" placeholder="请选择预设规则">
              <t-option v-for="item in presetsRuleOptions" :key="item.id" :label="item.presetName" :value="item.id" />
            </t-select>
          </t-form-item>

          <t-form-item label="选择平台" name="platform" :label-width="68" requiredMark>
            <t-select v-model="formData.platform" @change="onPlatformChange" placeholder="请选择所属平台">
              <t-option key="0" label="CC-1.0" :value="0" />
              <t-option key="1" label="TNCS" :value="1" />
              <t-option key="2" label="CC-2.0" :value="2" />
            </t-select>
          </t-form-item>

          <t-form-item label="所属企业" name="company" :label-width="68" requiredMark v-show="formData.platform !== 1">
            <t-select v-model="formData.company" :filter="filterMethod" @change="onCompanyChange" placeholder="请选择所属企业">
<!--              <t-option key="" label="全部" value=""></t-option>-->
              <t-option v-for="item in companyOptions" :key="item.id" :label="item.agencyName" :value="item.agencyId" />
            </t-select>
          </t-form-item>

          <!--          // 1.0 机构-->
          <t-form-item label="所属机构" name="org" :label-width="68" requiredMark v-if="formData.platform !== 1">
            <t-select v-model="formData.org" :filter="filterMethod" @change="onOrgChange" placeholder="请选择所属机构">
<!--              <t-option key="" label="全部" value=""></t-option>-->
              <t-option v-for="item in orgOptions" :key="item.id" :label="item.agencyName" :value="item.agencyId" />
            </t-select>
          </t-form-item>

          <!--          TNCs 机构-->
          <t-form-item label="所属机构" name="org" :label-width="68" requiredMark v-if="formData.platform === 1">
            <t-select v-model="formData.org" :filter="filterMethod" @change="onOrgChange" placeholder="请选择所属机构">
<!--              <t-option key="" label="全部" value=""></t-option>-->
              <t-option v-for="item in orgOptions" :key="item.id" :label="item.projectName" :value="item.id" />
            </t-select>
          </t-form-item>

          <t-form-item label="所属部门" name="branch" :label-width="68" requiredMark v-show="formData.platform !== 1">
            <t-select v-model="formData.branch" :filter="filterMethod" @change="onBranchChange" placeholder="请选择所属部门">
<!--              <t-option key="" label="全部" value=""></t-option>-->
              <t-option v-for="item in branchOptions" :key="item.id" :label="item.agencyName" :value="item.agencyId"  />
            </t-select>
          </t-form-item>

          <t-form-item label="质检记录" name="checked" :label-width="56">
            <t-select v-model="formData.checked" clearable placeholder="请选择质检记录">
              <t-option key="0" label="未质检" :value="0" />
              <t-option key="1" label="已质检" :value="1" />
            </t-select>
          </t-form-item>

          <t-form-item class="formHandleBox" v-if="!isFold" style="width: 50%">
            <t-space size="small" style="gap: 0;">
              <t-button style="width: 80px" class="queryBtn hoverBlue" @click="checkedAll" :loading="allLoading">选择全部</t-button>
              <t-button style="width: 80px" class="resetBtn hoverLightBlue" @click="clearAll">清空全选</t-button>
              <t-button class="queryBtn hoverBlue" @click="handleQuery('reset')" v-permission="['report:cdr:queryPage']">查询</t-button>
              <t-button class="resetBtn hoverLightBlue" @click="handleReset">重置</t-button>
              <span class="arrowCont" @click="handleArrow">
                 <span>{{ isFold ? '收起' : '展开' }}</span>
                 <svg-icon
                     :name="'icon-arrowTD'"
                     class-name="arrowTD-svg-icon"
                     :style="isFold === true ? 'transform: rotate(180deg)': ''"
                 ></svg-icon>
              </span>
            </t-space>
          </t-form-item>
        </t-form>
        <div class="titleFunnel" style="padding-top: 0;" v-if="isFold">
          <div class="blueLine"></div>
          <div class="title">高级筛选</div>
        </div>
        <t-form
            v-if="isFold"
            class="seniorForm"
            ref="seniorForm"
            :data="seniorFormData"
            :layout="'inline'"
            @reset="onSeniorReset">
          <t-form-item class="formDate" style="width: 50%">
            <t-space size="small" style="gap: 10px;">
              <div class="timeType">
                <span class="timeCheck" @click="timeClick('today')">今天</span>
                <span class="timeCheck" @click="timeClick('yesterday')">昨天</span>
                <span class="timeCheck" @click="timeClick('oneMonth')">一月</span>
                <span>时间</span>
              </div>
              <t-date-picker
                  enable-time-picker
                  allow-input
                  v-model="seniorFormData.startTime"
                  :defaultTime="['00:00:00']"
                  valueType="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择开始时间"
                  :disable-date="(date) => setDateStart(seniorFormData.endTime, date)"
              />
              <t-date-picker
                  enable-time-picker
                  allow-input
                  v-model="seniorFormData.endTime"
                  :defaultTime="['23:59:59']"
                  valueType="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择结束时间"
                  :disable-date="(date) => setDateEnd(seniorFormData.startTime, date)"
              />
            </t-space>
          </t-form-item>
          <t-form-item label="录音时长" name="" :label-width="56" class="timeRangeBox" style="width: 25%">
            <t-range-input :onBlur="onRangeBlur" :onChange="onRangeChange" v-model="inputValue"/>
            <span class="miao">秒</span>
          </t-form-item>
          <t-form-item label="呼叫类型" name="callType" :label-width="56" style="width: 25%">
            <t-select v-model="seniorFormData.callType" placeholder="请选择呼叫类型">
              <t-option key="1" label="呼入" :value="1" />
              <t-option key="2" label="呼出" :value="2" />
              <t-option v-if="formData.platform === 0" key="3" label="内线" :value="3" />
            </t-select>
          </t-form-item>

          <t-form-item label="质检范围" :label-width="56" name="checkRange" style="width: 50%">
            <t-radio-group v-model="seniorFormData.checkRange" @change="onRadioChange">
              <t-radio :value="1" style="margin-right: 10px;">不抽检</t-radio>
              <t-radio :value="0" style="margin-right: 10px;">抽检</t-radio>
            </t-radio-group>
            <t-space  v-if="seniorFormData.checkRange === 0" class="chouJan" style="gap: 0">
              <t-select
                  style="width: 88px; padding: 0"
                  v-model="whichType"
                  placeholder=""
              >
                <t-option :key="1" label="固定数量" :value="1" />
                <t-option :key="0" label="固定比例" :value="0" />
              </t-select>
              <t-input-number theme="normal" v-model="typeNum" class="numInput" placeholder="请输入数字"></t-input-number>
              <span class="c_label">{{ ['%', '条'][whichType] }}</span>
            </t-space>
          </t-form-item>
        </t-form>
        <div class="handleSeniorBox" v-if="isFold">
          <div class="saveBox">
            <span  @click="handleSaveRule" v-permission="['preset:save']">
              <svg-icon
                  :name="'icon-save'"
                  class-name="save-svg-icon"
              ></svg-icon>
            保存为预设条件
            </span>
          </div>
          <div class="handleBox handleTwoBox">
            <t-button style="width: 80px" class="queryBtn hoverBlue" @click="checkedAll" :loading="allLoading">选择全部</t-button>
            <t-button style="width: 80px" class="resetBtn hoverLightBlue" @click="clearAll">清空全选</t-button>
            <t-button class="queryBtn hoverBlue" @click="handleQuery('reset')" v-permission="['report:cdr:queryPage']">查询</t-button>
            <t-button class="resetBtn hoverLightBlue" @click="handleReset">重置</t-button>
            <span class="arrowCont" @click="handleArrow">
               <span>{{ isFold ? '收起' : '展开' }}</span>
               <svg-icon
                   :name="'icon-arrowTD'"
                   class-name="arrowTD-svg-icon"
                   :style="isFold === true ? 'transform: rotate(180deg)': ''"
               ></svg-icon>
            </span>
          </div>
        </div>
      </div>

    </div>
    <div class="tableBox">
      <div style="position: relative;">
        <t-table
            :loading="isLoading"
            :height="tableHeight"
            row-key="linkedid"
            :columns="tableState.columns"
            :data="tableState.tableData"
            :selected-row-keys="selectedRowKeys"
            @select-change="handleSelectChange"
        >
          <template #title-filter-columns>
            <div class="funnel" style="display: flex; align-items: center">
              <svg-icon
                  :name="'icon-funnel'"
                  class-name="funnel-svg-icon"
              ></svg-icon>
            </div>
          </template>
        </t-table>
        <div class="emptyBox" v-if="tableState.tableData.length === 0">
          <svg-icon
              :name="'icon-emptyTable'"
              class-name="emptyTable-svg-icon"
          ></svg-icon>
          <span>暂无数据</span>
        </div>
      </div>
    </div>
    <div class="footerBox">
      <t-pagination
          v-model="current"
          v-model:pageSize="pageSize"
          :pageSizeOptions="[10, 20, 30, 50]"
          :total="totalNum"
          size="small"
          show-jumper
          @page-size-change="onPageSizeChange"
          @current-change="onCurrentChange"
      />
    </div>

    <t-dialog
        v-model:visible="addVisible"
        width="361"
        :header="newTitle"
        :closeOnOverlayClick="false"
        :on-confirm="onConfirmAnother"
        :onClose="closeNewDialog"
    >
      <p>本次任务中录音共 <span class="num" v-if="selectedRowKeys">{{selectedRowKeys.length}}条</span></p>
      <div class="labelName">质检模版</div>
      <t-select :min-collapsed-num="2" multiple v-model="templateIds" placeholder="请选择质检模版" style="height: 28px">
        <t-option v-for="item in templateOptions" :key="item.id" :label="item.templateName" :value="item.id"/>
      </t-select>
      <div class="noteText" v-if="seniorFormData.type === 2">
        <svg-icon
            :name="'icon-warn'"
            class-name="warn-svg-icon"
        ></svg-icon>
        人工质检与智能质检共用模板
      </div>
    </t-dialog>

    <t-dialog
        v-model:visible="saveVisible"
        class="ruleDialog"
        width="385"
        header="新增预设规则"
        :onClose="onClose"
        destroy-on-close
    >
      <t-form
          ref="ruleForm"
          :data="ruleData"
          :label-align="'top'"
          :rules="AHEAD_RULES">
        <t-form-item label="预设规则名称" name="presetName">
          <t-input v-noSpace="ruleData.presetName" v-model="ruleData.presetName" placeholder="请输入预设规则名称"></t-input>
        </t-form-item>
        <t-form-item class="handleRuleBox">
          <t-space size="small">
            <t-button theme="default" variant="base" @click="cancelPreset">取消</t-button>
            <t-button class="hoverBlue" theme="primary" type="submit" @click="savePreset">保存</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script lang="jsx" setup>
import {nextTick, reactive, ref, getCurrentInstance, onMounted, onUnmounted, watch} from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { debounce } from "../../utils/tools";
import {cc0AgencyList, TNCsAgencyList, cc2AgencyList} from "../../api/commonApi";
import cache from '@/utils/cache.js'
import {cc1List, cc2List, detailPreset, getTemplate, newPreset, newTask, requestRuleList, tncsList} from "../../api/qualityTask";
const pageInstance = getCurrentInstance()
import { usePageStore } from '@/pinia/page.js'
const store = usePageStore()
import { getTypeData, setDateStart, setDateEnd } from '@/hooks/useCheckDate.js'
// form 表单
const formData = reactive({
  platform: null,
  company: '',
  org: '',
  branch: '',
  checked: null,
  presetsRule: '', // 预设规则
});

const companyOptions = ref([]) // 企业options
const orgOptions = ref([]) // 机构options
const branchOptions = ref([]) // 部门options
const presetsRuleOptions = ref([]) // 预设规则 options
// 选择平台事件
const onPlatformChange = (type) => {
  getTableHeight()
  store.setFormCondition(type, '', '', '')
  formData.company = ''
  companyOptions.value = []
  formData.org = ''
  orgOptions.value = []
  formData.branch = ''
  branchOptions.value = []
  // formData.presetsRule = ''
  // formData.presetsRuleOptions = []
  handleReset()
  getCompanyList(type)
}
const getCompanyList = (type) => {
  if(type === 0) { // 企业请求 1.0 接口
    let data = {
      agencyId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId']
    }
    cc0AgencyList(data).then(res => {
      companyOptions.value = res.data
    })
  } else if(type === 1) { // 机构请求 TNCs 接口
    TNCsAgencyList().then(res => {
      orgOptions.value = res.data
    })
  } else if(type === 2) {
    let data = {
      agencyId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId']
    }
    cc2AgencyList(data).then(res => {
      companyOptions.value = res.data
    })
  }
}
// 选择企业事件
const onCompanyChange = (type) => {
  store.setFormCondition(formData.platform, type, '', '')
  formData.org = ''
  orgOptions.value = []
  formData.branch = ''
  branchOptions.value = []
  // formData.presetsRule = ''
  // formData.presetsRuleOptions = []
  handleReset()
  // 获取机构options
  if(formData.platform === 0) {
    getOrgList(type)
  } else if(formData.platform === 2) {
    getOrgList2(type)
  }
}
const getOrgList = (type) => {
  let data = {
    agencyId: type
  }
  cc0AgencyList(data).then(res => {
    orgOptions.value = res.data
  })
}
const getOrgList2 = (type) => {
  let data = {
    agencyId: type
  }
  cc2AgencyList(data).then(res => {
    orgOptions.value = res.data
  })
}
// 机构选择事件
const onOrgChange = (type) => {
  store.setFormCondition(formData.platform, formData.company, type, '')
  formData.branch = ''
  branchOptions.value = []
  // formData.presetsRule = ''
  // formData.presetsRuleOptions = []
  handleReset()

  if(formData.platform === 0) {
    getBranchList(type)
  } else if(formData.platform === 2) {
    getBranchList2(type)
  }
}
const getBranchList = (type) => {
  let data = {
    agencyId: type
  }
  cc0AgencyList(data).then(res => {
    branchOptions.value = res.data
  })
}
const getBranchList2 = (type) => {
  let data = {
    agencyId: type
  }
  cc2AgencyList(data).then(res => {
    branchOptions.value = res.data
  })
}
// 部门选择事件
const onBranchChange = (type) => {
  store.setFormCondition(formData.platform, formData.company, formData.org, type)
  // formData.presetsRule = ''
  // formData.presetsRuleOptions = []
}

// 获取预设规则数据
const getRuleOptions = () => {
  let id = JSON.parse(cache.getLocalstorage('authInfo'))['agencyId']
  requestRuleList(id).then(res => {
    presetsRuleOptions.value = res.data
  })
}
// 预设规则选择事件
const onPresetRuleChange = (id) => {
  resetHeightForm()
  // 获取规则详情
  detailPreset(id).then( async res => {
    if(res.code === 0) {
      let data = res.data
      if(data.platform === 0) { // cc1.0
        formData.company = data.qualityProject.substring(0, 5) // 企业
        // 获取机构options
        const res = await cc0AgencyList({ agencyId: formData.company })
        orgOptions.value = res.data
        formData.org = data.qualityProject.substring(0, 8) // 机构

        const res1 = await cc0AgencyList({ agencyId: data.qualityProject.substring(0, 8) })
        branchOptions.value = res1.data
        formData.branch = data.qualityProject.substring(0, 11) //部门
      } else if(data.platform === 1) { // TNCs
        // 获取机构
        const res = await TNCsAgencyList()
        orgOptions.value = res.data
        formData.org = data.qualityProject * 1
      } else {
        formData.company = data.qualityProject.substring(0, 5) // 企业
        // 获取机构options
        const res = await cc2AgencyList({ agencyId: formData.company })
        orgOptions.value = res.data
        formData.org = data.qualityProject.substring(0, 8) // 机构

        const res1 = await cc2AgencyList({ agencyId: data.qualityProject.substring(0, 8) })
        branchOptions.value = res1.data
        formData.branch = data.qualityProject.substring(0, 11) //部门
      }

      function setForm() {
        formData.platform = data.platform
        seniorFormData.startTime = data.startTime
        seniorFormData.endTime = data.endTime

        inputValue.value[0] = data.recordMin
        inputValue.value[1] = data.recordMax

        seniorFormData.callType = data.callType
        seniorFormData.checkRange = data.checkRange
        if(data.checkRange === 0) {
          if(data.fixedNumber) {
            whichType.value = 0
            typeNum.value = data.fixedNumber
          }
          if(data.fixedRatio) {
            whichType.value = 1
            typeNum.value = data.fixedRatio
          }
        }
      }

      await setForm()

      await handleQuery()
    }
  })
}

let isFold = ref(false)
const handleArrow = () => {
  isFold.value = !isFold.value
}
// 高级form表单
const seniorFormData = reactive({
  startTime: '',
  endTime: '',
  recordMin: undefined,
  recordMax: undefined,
  callType: null,
  checkRange: 1,
  type: null
});
const defaultType = ref(1)
const whichType = ref(null)
const typeNum = ref(null)

const inputValue = ref([])
// 范围输入框事件
const onRangeChange = (value) => {
  if(value[0] !== undefined && isNaN(value[0] * 1)) {
    inputValue.value[0] = value[0].replace(/\D+/g, '')
  }
  if(value[1] !== undefined && isNaN(value[1] * 1)) {
    inputValue.value[1] = value[1].replace(/\D+/g, '')
  }
  seniorFormData.recordMin = value[0]
  seniorFormData.recordMax = value[1]
}
const onRangeBlur = (value) => {
  if(value[0] !== undefined && value[1] !== undefined && value[0] * 1 > value[1] * 1) {
    MessagePlugin.info('录音时长开始大于结束')
  }
}
const onRadioChange = (type) => {
  console.log(type)
  if(type === 0) {
    whichType.value = 1
  } else {
    whichType.value = null
  }

  typeNum.value = null
}

const onSeniorReset = () => {}
// 保存预设条件
const saveVisible = ref(false)
const handleSaveRule = () => {
  if(formData.platform !==1 && formData.branch === '') return MessagePlugin.error('请选择机构')
  if(formData.platform ===1 && formData.org === '') return MessagePlugin.error('请选择机构')
  // if(seniorFormData.startTime === '') return MessagePlugin.error('请选择开始时间')
  // if(seniorFormData.endTime === '') return MessagePlugin.error('请选择结束时间')
  // if(seniorFormData.recordMax === undefined || seniorFormData.recordMin === undefined) return MessagePlugin.error('请输入录音时长')
  // if(seniorFormData.callType === null) return MessagePlugin.error('请选择呼叫类型')
  // if(seniorFormData.checkRange === null) return MessagePlugin.error('请选择质检范围')
  if(seniorFormData.checkRange === 0) { // 抽检
    if(whichType.value === null) return MessagePlugin.error('请选择抽检类型')
    if(typeNum.value === null || typeNum.value === undefined) return MessagePlugin.error('请输入抽检数量或比例')
    if(whichType.value === 0) { // 固定比例
      if(seniorFormData.fixedRatio) delete seniorFormData.fixedRatio
      seniorFormData.fixedNumber = typeNum.value
    } else { // 固定数量
      if(seniorFormData.fixedNumber) delete seniorFormData.fixedNumber
      seniorFormData.fixedRatio = typeNum.value
    }
  }
  if(seniorFormData.fixedNumber && seniorFormData.fixedNumber > 100) {
    return MessagePlugin.error('质检范围固定比例请输入小于 100 的数字')
  }
  // console.log(seniorFormData)
  // return
  saveVisible.value = true
}
const AHEAD_RULES = {
  presetName: [ { required: true, message: '请输入预设规则名称' ,type: 'error', trigger: 'blur'}]
}
const ruleData = reactive({
  presetName: ''
});
const onClose = () => {
  pageInstance.refs.ruleForm.reset()
}
// 保存预设规则
const savePreset = () => {
  let id = formData.platform === 1 ? formData.org : formData.branch // 区分 TNCs与cc
  let data = {
    projectId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId'],
    qualityProject: id,
    platform: formData.platform,
    presetName: ruleData.presetName,
    ...seniorFormData
  }

  newPreset(data).then(res => {
    if(res.code === 0) {
      MessagePlugin.success('新增预设规则成功')
      pageInstance.refs.ruleForm.reset()
      saveVisible.value = false
      getRuleOptions()
    }
  }).catch(error => {
    saveVisible.value = false
  })
}
// 关闭预设规则弹窗
const cancelPreset = () => {
  pageInstance.refs.ruleForm.reset()
  saveVisible.value = false
}

// 时间选择事件
const timeClick = (type) => {
    seniorFormData.startTime = getTypeData(type, true).startTime
    seniorFormData.endTime = getTypeData(type, true).endTime
}

// 查询
const isLoading = ref(false)
const handleQuery = (flag) => {
  if(formData.platform === 0 || formData.platform === 2) { // 调用1.0接口

    if(formData.company === '') return MessagePlugin.error('请选择企业！')
    if(formData.org === '') return MessagePlugin.error('请选择机构！')
    if(formData.branch === '') return MessagePlugin.error('请选择部门！')

    formData.projectId = formData.branch

    if(flag === 'reset') {
      selectedRowKeys.value = []
      allLinkIds.value = []
      tableState.tableAllData = []
    }

    let data = {
      pageNo: flag === 'reset' ? 1 : current.value,
      pageSize: pageSize.value,
      option: seniorFormData.callType,
      ...formData,
      ...seniorFormData
    }
    isLoading.value = true

    if (formData.platform === 0) {
      cc1List(data).then(res => {
        if(res.code === 0) {
          tableState.tableData = res.data.list
          current.value = res.data['currPage']
          pageSize.value = res.data['pageSize']
          totalNum.value = res.data['totalCount']
        }
        isLoading.value = false
      }).catch(error => {
        isLoading.value = false
      })
    } else if(formData.platform === 2) {
      cc2List(data).then(res => {
        if(res.code === 0) {
          tableState.tableData = res.data.list
          current.value = res.data['currPage']
          pageSize.value = res.data['pageSize']
          totalNum.value = res.data['totalCount']
        }
        isLoading.value = false
      }).catch(error => {
        isLoading.value = false
      })
    }
  } else if (formData.platform === 1) { // 调用 TNCs 接口
    if(formData.org === '') return MessagePlugin.error('请选择机构！')
    formData.projectId = formData.org

    if(flag === 'reset') {
      selectedRowKeys.value = []
      allLinkIds.value = []
      tableState.tableAllData = []
      current.value = 1
    }

    let data = {
      pageNo: current.value,
      pageSize: pageSize.value,
      option: seniorFormData.callType,
      ...formData,
      ...seniorFormData
    }
    isLoading.value = true
    tncsList(data).then(res=> {
      if(res.code === 0) {
        tableState.tableData = res.data.list
        current.value = res.data['currPage']
        pageSize.value = res.data['pageSize']
        totalNum.value = res.data['totalCount']
      }
      isLoading.value = false
    }).catch(error => {
      isLoading.value = false
    })
  }
};
// 重置
const handleReset = () => {
  formData.presetsRule = ''
  formData.checked = null
  resetHeightForm()
}
// 重置高级筛选
const resetHeightForm = () => {
  seniorFormData.callType = null
  seniorFormData.startTime = ''
  seniorFormData.endTime = ''
  inputValue.value = []
  seniorFormData.recordMin = undefined
  seniorFormData.recordMax = undefined
  seniorFormData.checkRange = 1
  timeClick('today')
}
//table
const tableState = reactive({
  tableData: [],
  tableAllData: [],
  columns: [
    { colKey: '', title: 'title-filter-columns', width: '75'},
    { colKey: 'row-select', type: 'multiple', width: '46', className: () => {
        return 'custom-cell-select';
      }
    },
    { colKey: '',title: '序号', cell:(h, { row, rowIndex }) => {
        {{
          return rowIndex + (current.value - 1) * pageSize.value + 1 >= 10
              ? rowIndex + (current.value - 1) * pageSize.value + 1
              : "0" + (rowIndex + (current.value - 1) * pageSize.value + 1)
        }}
      }
    },
    { colKey: 'agentid', title: '座席工号' },
    { colKey: 'agentName', title: '座席名称' },
    { colKey: 'tela', title: '座席电话', ellipsis: true },
    { colKey: 'telb', title: '用户电话', ellipsis: true },
    { colKey: 'option', title: '呼叫类型', cell:(h, {row}) => {
      if(row.option === 'in' || row.option === 7) {
        return '呼入'
      } else if(row.option === 'ext') {
        return '内线'
      } else {
        return '呼出'
      }
    }},
    { colKey: 'billsec', title: '通话时长' },
    { colKey: 'start', title: '呼叫时间', ellipsis: true },
    { colKey: 'checked', title: '质检记录', align: 'center', cell:(h, {row}) => {
        return row.checked === 1
            ? <t-tag theme='success' variant="light-outline">
              已质检
            </t-tag>
            : <t-tag theme='warning' variant="light-outline">
              未质检
            </t-tag>
      }
    },
    { colKey: 'linkedid', title: 'UID', ellipsis: true },
  ],
})
const selectedRowKeys = ref([])
const handleSelectChange = (value, ctx) => {
  selectedRowKeys.value = value;
  allLinkIds.value = value
  tableState.tableAllData = ctx.selectedRowData
};
// table 高度变化
const tableHeight = ref(0)
const getTableHeight = () => {
 nextTick(() => {
   const otherHeight = pageInstance.refs.topBox.offsetHeight
   const windowHeight = window.innerHeight
   tableHeight.value = windowHeight - otherHeight - 170
 })
}
watch(() => isFold.value, (newVal, oldVal) => {
  getTableHeight()
})

// window窗口 变化
const getWindowInfo = () => {
  const info = {
    width: window.innerWidth,
    height: window.innerHeight
  }
  getTableHeight()
}
const resizeInfo = debounce(getWindowInfo, 0)
onMounted(() => {
  // 获取预设规则 list
  getRuleOptions()
  // 默认选中
  defaultSelection()
  getTableHeight()
  window.addEventListener('resize', resizeInfo);
})
// 有值默认选中
const defaultSelection = () => {
  timeClick('today')
  let formState = store.quality_form_id
  if(formState.platform !== null) { // 获取企业
    getCompanyList(formState.platform)
    formData.platform = formState.platform
  } else {
    onPlatformChange(0)
  }
  if(formState.company) { // 获取机构
    if(formState.platform === 0) {
      getOrgList(formState.company)
    } else if(formState.platform === 2) {
      getOrgList2(formState.company)
    }
    formData.company = formState.company
  }
  if(formState.org) { // 获取部门
    if(formState.platform === 0) {
      getBranchList(formState.org)
    } else if(formState.platform === 2) {
      getBranchList2(formState.org)
    }
    formData.org = formState.org
  }
  if(formState.branch) {
    formData.branch = formState.branch
    // timeClick('today')
    handleQuery()
  }
}

onUnmounted(() => {
  window.removeEventListener('resize', resizeInfo);
})

// 新增任务 dialog
const addVisible = ref(false)
const templateOptions = ref([])
const templateIds = ref([])
const newTitle = ref()
// const type = ref(0)
const handleAdd = (type) => {
  if(selectedRowKeys.value.length === 0) {
    return MessagePlugin.error('请勾选录音数据')
  }

  if(seniorFormData.checkRange === 0) { // 抽检
    if(whichType.value === null) return MessagePlugin.error('请选择抽检类型')
    if(typeNum.value === null || typeNum.value === undefined) return MessagePlugin.error('请输入抽检数量或比例')
    if(whichType.value === 0) { // 固定比例
      if(seniorFormData.fixedRatio) delete seniorFormData.fixedRatio
      seniorFormData.fixedNumber = typeNum.value
    } else { // 固定数量
      if(seniorFormData.fixedNumber) delete seniorFormData.fixedNumber
      seniorFormData.fixedRatio = typeNum.value
    }
  }
  if(seniorFormData.fixedNumber && seniorFormData.fixedNumber > 100) {
    return MessagePlugin.error('质检范围固定比例请输入小于 100 的数字')
  }

  // 新增获取模版数据
  let id = JSON.parse(cache.getLocalstorage('authInfo'))['agencyId']
  getTemplate(type, id).then(res => {
    templateOptions.value = res.data
  })
  addVisible.value = true
  seniorFormData.type = type // 质检类型
  if(type === 0) {
    newTitle.value = '新增智能质检任务'
  } else if(type === 1) {
    newTitle.value = '新增标签质检任务'
  }else {
    newTitle.value = '新增人工质检任务'
  }
}
// 选择新增任务
const clickQuality = (data) => {
  handleAdd(data.value)
}
const onConfirmAnother = () => {
  if(templateIds.value.length === 0) return MessagePlugin.error('请选择质检模版！')

  let id = formData.platform === 1 ? formData.org : formData.branch // 区分 TNCs与cc
  let data = {
    templateIds: templateIds.value,
    platform: formData.platform,
    asrProjectId: id, // 录音机构 id
    projectId: JSON.parse(cache.getLocalstorage('authInfo'))['agencyId'],
    ...seniorFormData
  }

  let idsData = []
  console.log(selectedRowKeys.value)
  selectedRowKeys.value.forEach(linkId => {
    tableState.tableAllData.forEach(item => {
      if(linkId === item.linkedid) {
        item.asrProjectId = data.asrProjectId
        item.time = item.end
        item.agentNumber = item.tela
        item.userNumber = item.telb
        item.agentId = item.agentid
        item.answer = item.answer ? item.answer : null
        item.duration = item.billsec
        if(item.option === 'in' || item.option === 7) {
          item.callType = 1
        } else {
          item.callType = 2
        }

        idsData.push(item)
      }
    })
  })

  data.taskDetailList = idsData
  // data.recording = "https://dkyrecord.obs.cn-north-4.myhuaweicloud.com:443/10129001001/20231128/20231128-132724-10129001001-19753922799-158xxxx3484-09912258236-cti4-1701149244.55186-36687.mp3"
  newTask(data).then(res => {
    if(res.code === 0) {
      selectedRowKeys.value = []
      allLinkIds.value = []
      tableState.tableAllData = []
      MessagePlugin.success('新增任务成功！')
      handleQuery()
    }
  })
  templateIds.value = []
  addVisible.value = false
}
const closeNewDialog = () => {
  templateIds.value = []
}
// 分页
const current = ref(1);
const pageSize = ref(10);
const totalNum = ref(0)
const onPageSizeChange = async (size) => {
  console.log('allLinkIds.value', allLinkIds.value)
  pageSize.value = size
  await handleQuery()
  await nextTick(() => {
    selectedRowKeys.value = allLinkIds.value
  })
};
const onCurrentChange = async (index, pageInfo) => {
  console.log('allLinkIds.value', allLinkIds.value)
  current.value = index
  await handleQuery()
  await nextTick(() => {
    selectedRowKeys.value = allLinkIds.value
  })
};

const filterMethod = (search, option) => {
  return option.label.indexOf(search) !== -1 || option.value.indexOf(search) !== -1
};



// 查询当前请求条件下所有数据
const getAllTableData = (totalNum) => {
  return new Promise(resolve => {
    if(formData.platform === 0 || formData.platform === 2) { // 调用1.0接口
      if(formData.company === '') return MessagePlugin.error('请选择企业！')
      if(formData.org === '') return MessagePlugin.error('请选择机构！')
      if(formData.branch === '') return MessagePlugin.error('请选择部门！')

      formData.projectId = formData.branch

      let data = {
        pageNo: 1,
        pageSize: totalNum,
        option: seniorFormData.callType,
        ...formData,
        ...seniorFormData
      }
      if (formData.platform === 0) {
        cc1List(data).then(res => {
          if(res.code === 0) {
            resolve(res.data.list)
          }
        })
      } else if(formData.platform === 2) {
        cc2List(data).then(res => {
          if(res.code === 0) {
            resolve(res.data.list)
          }
        })
      }
    } else if (formData.platform === 1) { // 调用 TNCs 接口
      if(formData.org === '') return MessagePlugin.error('请选择机构！')
      formData.projectId = formData.org
      let data = {
        pageNo: 1,
        pageSize: totalNum,
        option: seniorFormData.callType,
        ...formData,
        ...seniorFormData
      }

      tncsList(data).then(res=> {
        if(res.code === 0) {
          resolve(res.data.list)
        }
      })
    }
  })
};

let allLinkIds = ref([]) // 选择全部的id
// 选择全部
let allLoading = ref(false)
const checkedAll = async () => {
  if(totalNum.value === 0) return
  allLoading.value = true
  let response = await getAllTableData(totalNum.value)
  tableState.tableAllData = response
  let ids = []
  response.forEach(item => {
    ids.push(item['linkedid'])
  })
  allLinkIds.value = ids
  selectedRowKeys.value = ids
  allLoading.value = false
}
// 清空全选
const clearAll = () => {
  allLinkIds.value = []
  selectedRowKeys.value = []
  tableState.tableAllData = []
}
</script>

<style lang="scss" scoped>
.content {
  overflow: hidden;
  background-color: #EBECED!important;
  padding: 8px;
  position: relative;
  .topBox {
    padding: 20px 20px 0 20px;
    background-color: rgba(255, 255,255, 1);
    border-radius: 4px 4px 0 0;
    overflow: hidden;
    .title {
      font-size: 16px;
      font-weight: 600;
      line-height: 24px;
      color: rgba(51, 51, 51, 1);
      text-align: left;
      vertical-align: top;
      :deep(.t-button) {
        float: right;
        width: 101px;
        height: 28px;
        opacity: 1;
        border-radius: 3px;
        background: rgba(30, 117, 254, 1);
        padding: 5px 16px 5px 16px;
        font-size: 12px;
        font-weight: 400;
        line-height: 16.8px;
        color: rgba(255, 255, 255, 1);
        text-align: left;
        .add-svg-icon {
          height: 16px;
          width: 16px;
          margin-right: 5px;
        }
      }
      .batch {
        float: right;
        height: 28px;
        width: 88px;
        .batch-svg-icon {
          height: 16px;
          width: 16px;
          display: inline-block;
          margin-left: 8px;
        }
        :deep(.t-button) {
          height: 28px;
          width: 100%;
          padding: 0 8px;
          border-radius: 3px;
          .t-button__text {
            font-size: 12px;
            font-weight: 400;
            display: flex;
            justify-content: space-between;
            align-items: center;
          }
        }
        //:deep(.t-button):hover {
        //  background: var(--Brand-Brand1-Light, #EDF2FD) !important;
        //  color: var(--Brand-Brand6-Hover, #458DFF) !important;
        //  //border: 1px solid var(--Brand-Brand6-Hover, #458DFF) !important;
        //}
      }
    }
    .line {
      height: 0;
      opacity: 1;
      background: rgba(204, 204, 204, 1);
      border: 1px solid rgba(239, 242, 245, 1);
      margin-top: 21px;
    }
    .formBox {
      .titleFunnel {
        padding-top: 20px;
        padding-bottom: 16px;
        display: flex;
        justify-content: left;
        align-items: center;
        .blueLine {
          display: inline-block;
          width: 4px;
          height: 16px;
          opacity: 1;
          border-radius: 2px;
          margin-right: 5px;
          background: rgba(30, 117, 254, 1);
        }
        .title {
          font-size: 13px;
          font-weight: 500;
          color: rgba(0, 0, 0, 1);
          text-align: left;
          vertical-align: top;
        }
      }
      .seniorForm {
        width: 100%;
        padding-top: 0;
        padding-bottom: 20px;
        :deep(.t-form__item) {
          padding-right: 10px;
        }
        :deep(.t-form__item):nth-child(1) {
          .t-form__label--right {display: none}
          .t-form__controls {
            margin-left: 0 !important;
          }
          .t-space {
            width: 100%;
            .timeCheck {
              font-size: 12px;
              font-weight: 400;
              color: rgba(30, 117, 254, 1);
              cursor: pointer;
            }
          }
          .t-space-item:nth-child(1) {
            width: 126px;
          }
          .t-space-item:nth-child(2) {
            width: calc((100% - 146px) / 2);
          }
          .t-space-item:nth-child(3) {
            width: calc((100% - 146px) / 2);
          }
          .t-date-picker {
            height: 28px;
            width: 100%;
            .t-input {
              height: 28px;
            }
          }
          .timeType {
            float: left;
            width: 126px;
            text-align: left;
            height: 28px;
            line-height: 28px;
            span {
              margin-right: 10px;
              font-size: 12px;
              font-weight: 400;
              color: rgba(0, 0, 0, 0.9);
            }
            span:nth-child(4) {
              margin-right: 0;
            }
          }
        }
        :deep(.t-form__item):nth-child(3) {
          padding-right: 0;
        }
        :deep(.t-form__item):nth-child(4) {
          padding-right: 10px;
        }
        :deep(.t-input-group) {
          width: 100%;
          .t-input__wrap {
            width: calc(50% - 8px)!important;
          }
        }
        :deep(.t-radio__label) {
          font-size: 12px;
          font-weight: 400;
          color: rgba(92, 91, 91, 1);
        }
        .timeRangeBox {
          .miao {
            display: inline-block;
            height: 28px;
            width: 42px;
            line-height: 28px;
            text-align: center;
            background: rgba(243, 243, 243, 1);
            border: 1px solid rgba(220, 220, 220, 1);
            border-radius: 0 2px 2px 0;
            border-left: none;
            font-size: 14px;
            font-weight: 400;
            color: rgba(12, 13, 14, 1);
          }
          :deep(.t-range-input) {
            border-radius: 2px 0 0 2px;
          }
        }
      }
      .handleSeniorBox {
        height: 30px;
        line-height: 30px;
        display: flex;
        .saveBox {
          flex: 1;
          font-size: 12px;
          font-weight: 400;
          color: rgba(30, 117, 254, 1);
          text-align: left;
          span {
            cursor: pointer;
            display: inline-block;
          }
          .save-svg-icon {
            height: 16px;
            width: 16px;
            position: relative;
            top: 3px;
          }
        }
        .handleBox {
          flex: 1;
          text-align: right;
          .queryBtn {
            border: none;
            width: 56px;
            height: 30px;
            opacity: 1;
            border-radius: 3px;
            background: rgba(30, 117, 254, 1);
            font-size: 12px;
            font-weight: 400;
            color: rgba(255, 255, 255, 1);
            text-align: center;
          }
          .resetBtn {
            margin: 0 10px;
            width: 56px;
            height: 30px;
            opacity: 1;
            border-radius: 3px;
            background: rgba(236, 242, 254, 1);
            border: 0.5px solid rgba(30, 117, 254, 1);
            font-size: 12px;
            font-weight: 400;
            color: rgba(30, 117, 254, 1);
            text-align: center;
          }
          .arrowCont {
            display: inline-block;
            height: 30px;
            position: relative;
            min-width: 40px !important;
            cursor: pointer;
            span {
              font-size: 12px;
              font-weight: 500;
              color: rgba(138, 138, 138, 1);
            }
            .arrowTD-svg-icon {
              height: 16px;
              width: 16px;
              cursor: pointer;
              display: inline-block;
              vertical-align: middle;
            }
          }
        }
        .handleTwoBox {
          .t-button {
            margin: 0 5px !important;
          }
        }
      }
    }
    :deep(.t-form) {
      padding: 16px 0 20px 0;
      .t-form-inline {
        row-gap: 16px !important;
      }
      .t-form__item {
        width: 25%;
        height: 28px;
        margin-right: 0!important;
        padding-right: 10px;
        .t-range-input {
          height: 28px;
        }
        .t-form__label--right {
          text-align: left;
          padding-right: 0;
          font-size: 12px;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.9);
        }
        .t-select__wrap {
          .t-input {
            height: 28px;
          }
        }
      }
      .t-form__item:nth-child(4) {
        padding-right: 0;
      }
      .formHandleBox {
        margin-left: auto;
        text-align: right;
        padding-right: 0;
        .t-space {
          margin-left: auto;
          justify-content: center;
          align-items: center;
          .queryBtn {
            border: none;
            width: 56px;
            height: 30px;
            opacity: 1;
            border-radius: 3px;
            background: rgba(30, 117, 254, 1);
            font-size: 12px;
            font-weight: 400;
            color: rgba(255, 255, 255, 1);
            text-align: center;
          }
          .resetBtn {
            width: 56px;
            height: 30px;
            opacity: 1;
            border-radius: 3px;
            background: rgba(236, 242, 254, 1);
            border: 0.5px solid rgba(30, 117, 254, 1);
            font-size: 12px;
            font-weight: 400;
            color: rgba(30, 117, 254, 1);
            text-align: center;
          }
          .arrowCont {
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            span {
              font-size: 12px;
              font-weight: 500;
              color: rgba(138, 138, 138, 1);
            }
            .arrowTD-svg-icon {
              height: 16px;
              width: 16px;
              cursor: pointer;
            }
          }
          .t-space-item {
            .t-button {
              margin: 0 5px;
            }
          }
          .t-space-item:last-child {
            margin-right: 0;
          }
        }
        .t-form__controls {
          margin-left: 0 !important;
        }
      }
    }
  }
  .tableBox {
    padding-top: 8px;
    background-color: white!important;
    :deep(.t-table__content) {
      .t-tag {
        margin: 0 auto;
        width: 62px;
        height: 24px;
        opacity: 1;
        border-radius: 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 5px 12px 5px 12px;
        font-size: 12px;
        font-weight: 400;
      }
      .t-tag--warning {
        background: rgba(235, 235, 235, 1);
        border: none ;
        color: rgba(122, 122, 122, 1);
      }
      .t-tag--success {
        background: rgba(233, 246, 242, 1);
        border: none ;
        color: rgba(0, 184, 122, 1);
      }
    }
    :deep(.t-table__header) {
      border-right: 4px !important;
      tr {
        th {
          padding: 7px 10px;
        }
        th:nth-child(1) {
          padding: 7px 0 7px 30px;
        }
        th:nth-child(2) {
          //padding-right: 0;
        }
        th:nth-child(3) {
          padding-left: 0;
        }
      }

    }
    :deep(.t-table__body) {
      tr {
        td {
          background-color: #FFFFFF;
          padding: 6px 10px;
          box-sizing: border-box;
        }
        td:nth-child(3) {
          padding-left: 0;
        }
      }
    }
    .funnel-svg-icon {
      width: 16px;
      height: 15.84px;
      cursor: pointer;
    }
    :deep(.custom-cell-select) {
      padding-right: 0!important;
    }
    :deep(.custom-cell-index) {
      padding-left: 0!important;
    }
  }
}
:deep(.t-dialog) {
  padding: 24px 22px 18px 22px;
  border-radius: 6px;
  p {
    font-size: 13px;
    font-weight: 400;
    color: rgba(89, 89, 89, 1);

    height: 26px;
    opacity: 1;
    border-radius: 6px;
    background: rgba(245, 246, 247, 1);

    padding: 2px 11px 2px 11px;
  }
  .num {
    font-size: 13px;
    font-weight: 400;
    text-decoration-line: underline;
    color: rgba(227, 77, 89, 1);
    text-align: left;
    vertical-align: top;
  }
  .labelName {
    margin-top: 18px;
    margin-bottom: 8px;
    font-size: 13px;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.9);
  }
  .noteText {
    margin-top: 10px;
      width: 200px;
      height: 28px;
      opacity: 1;
      border-radius: 7px;
      background: rgba(242, 242, 242, 1);
      display: flex;
      justify-content: flex-start;
      align-items: center;
      padding: 3px 10px 3px 10px;

      font-size: 12px;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.9);
      .warn-svg-icon {
        height: 16px;
        width: 16px;
        margin-right: 8px;
      }
  }
  .t-input.t-is-readonly {
    height: 28px;
  }
  .t-input__inner {
    font-size: 12px;
    font-weight: 400;
    color: rgba(12, 13, 14, 1);
    text-align: left;
    vertical-align: top;
  }
  .t-dialog__cancel {
    background-color: white;
    border: none;
    width: 60px;
    height: 28px;
  }
  .t-dialog__confirm {
    width: 60px;
    height: 28px;
    opacity: 1;
    border-radius: 3px;
    background: rgba(30, 117, 254, 1);
  }
  .t-dialog__confirm:hover {
    background: var(--Brand-Brand6-Hover, #458DFF) !important;
    color: var(--text-icon-font-wh-190-anti, rgba(255, 255, 255, 0.90)) !important;
  }
}
:deep(.t-table__empty) {
  display: none;
}
.emptyBox {
  position: absolute;
  height: 116px;
  width: 69px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  .emptyTable-svg-icon {
    height: 62px;
    width: 69px;
  }
  span {
    font-size: 12px;
    font-weight: 400;
    color: rgba(92, 91, 91, 1);
  }
}
:deep(.ruleDialog .t-dialog__wrap .t-dialog__position .t-dialog) {
  .t-dialog__footer {
    display: none !important;
  }
  .t-dialog__body {
    padding-bottom: 0;
    .t-input {
      height: 28px;
    }
  }
}
.handleRuleBox {
  :deep(.t-form__label) {
    font-size: 14px;
    font-weight: 400;
    color: rgba(227, 60, 100, 0.9);

  }
  :deep(.t-form__controls) {
    text-align: right;
  }
  :deep(.t-form__controls-content) {
    display: inline-block;
    position: absolute;
    right: 0;
  }
  .t-button--theme-default {
    background-color: white;
    border: none;
    width: 60px;
    height: 28px;
  }
  .t-button--theme-primary {
    width: 60px;
    height: 28px;
    opacity: 1;
    border-radius: 3px;
    background: rgba(30, 117, 254, 1);
  }
}
.paddingBottom {
  padding-bottom: 20px !important;
}
.lineBottom {
  margin-bottom: 4px;
}
.chouJan {
  width:calc(100% - 128px) !important;
  border: 1px solid rgba(220, 220, 220, 1);
  border-radius: 3px;
  :deep(.t-select-input) {
    .t-input__wrap {

      .t-input {
        //border: 1px solid rgba(220, 220, 220, 1);
        border-radius: 0;
        border: none;
        border-right: 1px solid rgba(220, 220, 220, 1);
        background: rgba(243, 243, 243, 1);
      }
    }

  }
  .numInput {
    width: 253px;
    :deep(.t-input) {
      height: 28px;
      border-radius: 0;
      border: none;
    }
  }
  .c_label {
    display: inline-block;
    height: 28px;
    width: 42px;
    line-height: 28px;
    text-align: center;
    background: rgba(243, 243, 243, 1);
    border-radius: 0 2px 2px 0;
    border-left: 1px solid rgba(220, 220, 220, 1);
    font-size: 14px;
    font-weight: 400;
    color: rgba(12, 13, 14, 1);
  }
  :deep(.t-space-item):nth-child(1) {
    width: 88px !important;
  }
  :deep(.t-space-item):nth-child(2) {
    width: calc(100% - 130px);
    .t-input-number {
      width: 100%;
    }
  }
  :deep(.t-space-item):nth-child(3) {
    width: 42px;
  }
}
.footerBox {
  position: absolute;
  bottom: 8px;
  overflow: hidden;
  background-color: white;
  width: calc(100% - 16px);
  border-radius: 0 0 4px 4px;
}
:deep(.t-input .t-input__suffix:not(:empty)) {
    margin-left: 0 !important;
}
</style>
